/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.cjt2325.cameraview.slice;

import com.cjt2325.cameralibrary.util.LogUtil;
import com.cjt2325.cameraview.ResourceTable;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;

/**
 * Camera MainSlice
 */
public class CameraMainSlice extends AbilitySlice {
    private static final int SLICE_CODE = 0;
    private Image image;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_layout_main);
        Component componentById = findComponentById(ResourceTable.Id_photo);
        if (componentById instanceof Image) {
            image = (Image) componentById;
            findComponentById(ResourceTable.Id_iv)
                    .setClickedListener(component ->
                            presentForResult(new MainAbilitySlice(), new Intent(), SLICE_CODE));
        }
    }

    @Override
    protected void onActive() {
        super.onActive();
        getWindow().setStatusBarVisibility(Component.INVISIBLE);
    }

    @Override
    protected void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onResult(int requestCode, Intent resultIntent) {
        super.onResult(requestCode, resultIntent);
        try {
            if (requestCode == SLICE_CODE && resultIntent != null) {
                if (resultIntent.hasParameter("PHOTO_URL")) {
                    String photoUrl = resultIntent.getStringParam("PHOTO_URL");
                    if (photoUrl == null || "".equals(photoUrl)) {
                        return;
                    }
                    PixelMap pixelMa = ImageSource.create(photoUrl, null).createPixelmap(null);
                    image.setPixelMap(pixelMa);
                    LogUtil.info(LogUtil.DEFAULT_TAG, "onResult photoUrl:" + photoUrl);
                }
            }
        } catch (Exception vrp) {
            LogUtil.info(LogUtil.DEFAULT_TAG, "onResult error:" + vrp.getMessage());
        }
    }
}
